package com.datam.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.datam.dao.CompanyInfoDAO;
import com.datam.dao.SysUserDAO;
import com.datam.dao.YJDAO;
import com.datam.domain.CompanyInfoDO;
import com.datam.domain.SysUserDO;
import com.datam.query.QueryCompanyInfo;
import com.datam.query.QuerySysUser;
import com.datam.utils.DMResult;
import com.datam.utils.VerifyUtils;
import com.dm.controller.SysUserController;
import com.dm.utils.HttpClient;
import com.dm.utils.RespsonseResult;


@Controller
public class UserController {
	
	private static Logger logger = LoggerFactory.getLogger(UserController.class);

	
	
	@Autowired
	SysUserDAO sysUserDAO ;
	
	//@Value("${openurl}")
    private String url = "http://182.92.185.221/";
    //private String url = "http://150.109.148.212/";
    
    @Autowired
	YJDAO yJDAO ; 
	
	
	
	@RequestMapping("Home/getCode")
	public void getCode(HttpServletRequest request, HttpServletResponse response){
		VerifyUtils vu = new VerifyUtils();
		vu.getRandcode(request, response);
	}
	
	@RequestMapping("Home/upUser")
	public  @ResponseBody Object  upUser(HttpServletRequest request, HttpServletResponse response,SysUserDO u ){
		sysUserDAO.updateSysUserByUserId(u);
		SysUserDO tmp = sysUserDAO.selectSysUserByUserId(u.getUserId());
		if(tmp.getCompanyInfo()!=null&&tmp.getType()!=0){
			CompanyInfoDO companyInfoDO = new CompanyInfoDO();
			companyInfoDO.setID(Long.valueOf(tmp.getCompanyInfo()));
			companyInfoDO.setPASSWORD(tmp.getPassword());
			companyInfoDAO.updateCompanyInfoById(companyInfoDO);
		}
		
		return new DMResult("修改成功",true); 
	}
	@RequestMapping("Home/exit")
	public @ResponseBody Object exitSys(HttpServletRequest request,QuerySysUser querySysUser){
		logger.info("退出登录");
		 RespsonseResult result = new RespsonseResult();
		 try {
			 request.getSession().setAttribute("user", null);
			 result.setCode("0");
			 result.setMsg("退出成功");
		} catch (Exception e) {
			e.printStackTrace();
			result.setMsg("退出失败");
			result.setCode("1");
		}
		return result;
	}
	
	@Autowired
	CompanyInfoDAO companyInfoDAO;
	
	
	@RequestMapping("Home/getuserbycode")
	public @ResponseBody Object getuserbycode(HttpServletRequest request, HttpServletResponse response,String code){
		try {
			if(code!=null){
				String wxInfo = HttpClient.sendGetRequest(url+"userinfo?usercode="+code, null,new  HttpHeaders());
				System.out.println("wxInfo:"+wxInfo);
				JSONObject wxMap = JSON.parseObject(wxInfo);
				String openId = wxMap.getString("openId");
				System.out.println("openId:"+openId);
				if(openId==null){
					System.out.println("获取微信信息失败");
					return new DMResult("获取微信信息失败",false); 
				}
				QuerySysUser querySysUser = new QuerySysUser();
				querySysUser.setWxid(openId);
				List< SysUserDO > d = sysUserDAO.selectSysUserList(querySysUser);
				request.getSession().setAttribute("openinfo", wxMap);
				if(d!=null&&d.size()>0){
					logger.info("微信登录成功="+openId);
					SysUserDO user = d.get(0);
					request.getSession().setAttribute("userCid", user.getCompanyInfo());
					if(user.getType()!=0&&user.getCompanyInfo()!=null){
						CompanyInfoDO companyInfoDO = companyInfoDAO.selectCompanyInfoById(Long.valueOf(user.getCompanyInfo()));
						if(companyInfoDO!=null){
							user.setCompanyInfo(companyInfoDO.getNAME());
						}
					}
					if(user.getType()==0) user.setCompanyInfo("河南省文马科技有限公司");
					request.getSession().setAttribute("user", user);
					return new DMResult(user,"登录成功",true); 
				}else{
					logger.info("无用户信息="+openId);
					DMResult dr = new DMResult("无用户信息",false);
					dr.putOtherInfo("wxid", openId);
					return dr; 
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new DMResult("登录失败",false); 
		}
		return new DMResult("无用户信息",false); 
	}
	
	public static void main(String[] args) {
		String s = "[\"test\"]";
		JSON.parseArray(s, String.class);
	}
	@RequestMapping("Home/Login")
	public @ResponseBody Object login(HttpServletRequest request, HttpServletResponse response
								,String validateCode,String username,String password){
		try {
			String yzm = (String) request.getSession().getAttribute("RANDOMREDISKEY");
			if(!yzm.equals(validateCode)) return new DMResult("验证码错误");
			
			QuerySysUser querySysUser = new QuerySysUser();
			querySysUser.setCode(username);
			List< SysUserDO > d = sysUserDAO.selectSysUserList(querySysUser);
			if(d ==null || d.size()==0)  return new DMResult("用户不存在");
			
			SysUserDO user = d.get(0);
			if(!user.getPassword().equals(password)) return new DMResult("密码错误");
			String wxid = request.getParameter("wxid");
			logger.info("页面传过来的 wxid="+wxid);
			if(StringUtils.isNotBlank(wxid)){
				List<String> wx = new ArrayList<String>();
				String wxids = user.getWxid();
				logger.info("原有的  wxid="+wxids);
				if(StringUtils.isNotBlank(wxids)){
					wx.addAll(JSON.parseArray(wxids, String.class));
				}
				wx.add(wxid);
				user.setWxid(JSONArray.toJSONString(wx));
				logger.info("入库的  wxid="+JSONArray.toJSONString(wx));
				sysUserDAO.updateSysUserByUserId(user);
				request.getSession().setAttribute("openId", wxid);
				JSONObject wxMap = (JSONObject) request.getSession().getAttribute("openinfo");
				String IMG_URL = wxMap.getString("headImgUrl");
				String WX_NAME = wxMap.getString("nickName");
				String ID = wxid ; 
				String COMPANYID = user.getCompanyInfo();
				yJDAO.insertWxInfo(IMG_URL,WX_NAME,ID,COMPANYID);
				
			}
			request.getSession().setAttribute("userCid", user.getCompanyInfo());
			if(user.getType()!=0&&user.getCompanyInfo()!=null){
				CompanyInfoDO companyInfoDO = companyInfoDAO.selectCompanyInfoById(Long.valueOf(user.getCompanyInfo()));
				if(companyInfoDO!=null){
					user.setCompanyInfo(companyInfoDO.getNAME());
				}
			}
			if(user.getType()==0) user.setCompanyInfo("河南省文马科技有限公司");
			request.getSession().setAttribute("user", user);
			return new DMResult(user,"登录成功",true); 
		} catch (Exception e) {
			e.printStackTrace();
			return new DMResult("登录失败",false); 
		}
	}

}
